<script lang="ts">
/**
 * @author wyr
 * @description #19511 图片本地上传
 * @prop type string类型 判断类型是图片还是视频,图片是pic，视频的video
 * @event emit('on-done') 保存操作
 * @event emit('on-cancel') 取消操作
 */
import {
  Component,
  Vue,
  Prop,
  Watch,
  Mixins,
  Emit
} from "vue-property-decorator";
import { Action, namespace } from "vuex-class";
import { EventBus } from "feok-lib";
import { postApiAssetsFile } from "@/model";
import OSSPictureUpload from "@/components/OSSPictureUpload.vue";
import GroupSelect from "@/components/GroupSelect";

@Component({
  components: {
    OSSPictureUpload,
    GroupSelect
  }
})
export default class PhotoUpload extends Vue {
  @Prop({ type: String, default: "pic" }) public type!: string; // type判断类型是图片还是视频,图片是pic，视频的video
  get rules() {
    return {
      teamId: [
        { required: true, message: "此处为必填项", trigger: ["blur", "change"] }
      ],
      pics: [{ validator: this.checkPic, trigger: "blur" }]
    };
  }

  public btnLoading: boolean = false;
  public modalValue: boolean = false;
  public labelName: string = ""; // 标签名称
  public form: any = {
    labelIds: [], // 标签id
    pics: [], // 本地图片
    teamId: ""
  };

  // 取消
  public cancel() {
    this.$emit("on-cancel");
  }

  // 图片上传成功
  public onSuccess(response: any, file: any, fileList: any) {
    const obj = {
      name: file.name,
      url: file.response.url,
      type: "IMAGE", // 分类 IMAGE VIDEO FILE
      size: file.size // 文件大小
    };
    this.form.pics.push(obj);
  }

  // 图片移除
  public handleRemove(file: any, fileList: any) {
    const arr = this.form.pics.map((res: any) => res.url);
    const index = arr.findIndex((item: any) => {
      return item === file.response.url;
    });
    this.form.pics.splice(index, 1);
  }

  // 校验上传图片
  public checkPic(rule: any, value: any, callback: any) {
    if (value.length === 0) {
      callback(new Error("此处为必填项"));
    } else {
      callback();
    }
  }

  // 新增标签
  public addLabel() {
    this.modalValue = true;
  }

  // 关闭新增标签
  public async handleLabel(labelName: string) {
    // wyr-todo 走接口，新增标签
    //  await postV2ProductStandard({
    //     labelName: labelName,
    //   }).toPromise();
    this.modalValue = false;
    this.modalValue = false;
    if (labelName) {
      const ref = this.$refs.LabelsSelect as any;
      ref.onRefresh();
    } else {
      EventBus.$emit("error", "新增标签不能为空");
    }
  }

  // 确定
  private submitForm(formName: string) {
    const ref = this.$refs[formName] as any;
    ref.validate(async (valid: any) => {
      if (valid) {
        try {
          this.btnLoading = true;
          await postApiAssetsFile(
            this.form.pics.map((res: any) => ({
              ...res,
              groupId: this.form.teamId
            }))
          );
          EventBus.$emit("success", "操作成功");
          this.$emit("on-done", this.form.pics);
        } catch (err) {
          console.log(err);
        } finally {
          this.btnLoading = false;
        }
      } else {
        console.log("error submit!!");
        return false;
      }
    });
  }
}
</script>

<template>
  <div class="photo-upload">
    <el-form ref="form" :model="form" label-width="100px" :rules="rules" size="small">
      <el-form-item label="分组：" v-if="type==='pic'" prop="teamId">
        <GroupSelect
          v-model="form.teamId"
          :query="{type: 'IMAGE'}"
          placeholder="请选择"
          class="feok-input-lg"
        />
      </el-form-item>
      <el-form-item label="上传图片：" prop="pics" class="is-required">
        <div class="pic-team">
          <OSSPictureUpload
            multiple
            module-name="pic"
            @on-success="onSuccess"
            @on-remove="handleRemove"
            :limit="10"
          />
          <div class="tip">仅支持 gif、 jpeg、 png 3种格式, 大小不超过4.0 MB</div>
        </div>
      </el-form-item>
      <el-form-item style="margin-bottom:0px;">
        <el-button type="primary" @click="submitForm('form')" :loading="btnLoading">保存</el-button>
        <el-button @click="$emit('on-cancel')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="less">
.photo-upload {
  .pic-team {
    .tip {
      color: #aaa;
      font-size: 14px;
    }
  }
}
</style>